using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using Grid;
using UnityEngine;

public class SaveSystem
{
    public static void SaveFile(string filename, string saveData)
    {
        var savePath = Path.Combine(Application.persistentDataPath, $"{filename}.json");
        var fileStream = new FileStream(savePath, FileMode.Create);

        using (var writer = new StreamWriter(fileStream))
        {
            writer.Write(saveData);
        }
    }

    public static string LoadFile(string filename)
    {
        var savePath = Path.Combine(Application.persistentDataPath, $"{filename}.json");
        if (File.Exists(savePath))
        {
            using(var reader = new StreamReader(savePath))
            {
                return reader.ReadToEnd();
            }
        }
        else
        {
            Debug.LogError("Cannot find the save file!");
        }
        return null;
    }
    


    public class IgnoreUnityDeprecatedPropertiesResolver : DefaultContractResolver
    {
        private static readonly HashSet<string> DeprecatedProperties = new HashSet<string>
        {
            "rigidbody",
            "rigidbody2D",
            "camera",
            "light",
            "animation",
            // 在这里添加任何其他已知的弃用属性
        };

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);

            // 如果 GameObject 类型的属性已弃用，则忽略它
            if (property.DeclaringType == typeof(GameObject) && DeprecatedProperties.Contains(property.PropertyName))
            {
                property.ShouldSerialize = instance => false;
            }

            return property;
        }
    }
    
    
    public class IgnoreObsoletePropertiesResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);

            // 检查属性是否有 [Obsolete] 特性
            if (member.GetCustomAttribute<ObsoleteAttribute>() != null)
            {
                // 如果有，则忽略该属性
                property.ShouldSerialize = instance => false;
            }

            return property;
        }
    }

    public static void SaveObject(string filename, object saveData)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            ContractResolver = new IgnoreObsoletePropertiesResolver()
        };

        string json = JsonConvert.SerializeObject(saveData, settings);
        SaveFile(filename, json);
        // 然后将json字符串保存到文件
        Debug.Log("Save success!");
    }
    
    // public static void SaveObject(string filename, object saveData)
    // {
    //     JsonSerializerSettings settings = new JsonSerializerSettings
    //     {
    //         ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    //         ContractResolver = new IgnoreUnityDeprecatedPropertiesResolver()
    //     };
    //
    //     string json = JsonConvert.SerializeObject(saveData, settings);
    //     SaveFile(filename, json);
    //     Debug.Log("Save success!");
    // }

    // public static void SaveObject(string filename, object saveData)
    // {
    //     JsonSerializerSettings settings = new JsonSerializerSettings
    //     {
    //         ReferenceLoopHandling = ReferenceLoopHandling.Ignore // 设置忽略循环引用
    //     };
    //
    //     string json = JsonConvert.SerializeObject(saveData, settings);
    //     SaveFile(filename, json);
    //     Debug.Log("Save success!");
    // }
    //
    
    public static TSaveObject LoadSavedObject<TSaveObject>(string filename)
    {
        var saveData = LoadFile(filename);
        if(saveData != null)
        {
            var saveObject = JsonUtility.FromJson<TSaveObject>(saveData);
            // var saveObject = JsonConvert.DeserializeObject<TSaveObject>(saveData);
             
            return saveObject;
        }
        return default;
    }
    
    // public static T LoadSavedObject<T>(string filename)
    // {
    //     var saveData = LoadFile(filename);
    //     if (saveData != null)
    //     {
    //         try
    //         {
    //             JsonSerializerSettings settings = new JsonSerializerSettings
    //             {
    //                 ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    //                 ContractResolver = new IgnoreObsoletePropertiesResolver(),
    //                 MissingMemberHandling = MissingMemberHandling.Ignore, // 忽略JSON中的未知成员
    //                 Converters = new List<JsonConverter> { new TransformConverter() } // 添加自定义转换器
    //             };
    //
    //             var saveObject = JsonConvert.DeserializeObject<T>(saveData, settings);
    //             return saveObject;
    //         }
    //         catch (JsonSerializationException ex)
    //         {
    //             Debug.LogError($"JsonSerializationException occurred while deserializing the file {filename}: {ex.Message}");
    //         }
    //         catch (Exception ex)
    //         {
    //             Debug.LogError($"An exception occurred while deserializing the file {filename}: {ex.Message}");
    //         }
    //     }
    //     return default(T);
    // }

// 假设的 TransformConverter 实现
    // public class TransformConverter : JsonConverter
    // {
    //     public override bool CanConvert(Type objectType)
    //     {
    //         return objectType == typeof(Transform);
    //     }
    //
    //     public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    //     {
    //         // 序列化时忽略Transform，或者只处理位置、旋转和缩放
    //         // 由于Transform不能被直接反序列化，这里可以返回null或者一个新的Transform实例
    //         // 真正的实现应该根据您的需求来定
    //         return null;
    //     }
    //
    //     public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    //     {
    //         // Transform不能被直接序列化，但如果您需要序列化位置、旋转和缩放，可以在这里实现
    //         // 这个例子中不实现写操作，因为我们只关注反序列化
    //     }
    // }
}
